package com.junlaninfo.HandwritingLock;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by 辉 on 2020/8/23.
 * 通过原子类手写类似于reenLock的效果，原理是通过cas实现的
 */
public class DaXiongLock {
    private AtomicInteger atomicInteger=new AtomicInteger(0);
    //记录获取到锁的线程
    private  Thread currentThread;

    /*
      获取锁
     */
    public  boolean tryLock(){
        //如果能把状态修改为1,那么证明获取到锁
        boolean b = atomicInteger.compareAndSet(0, 1);
//        //修改不成功就自旋
//        if (!b){
//            while (true){
//                boolean b1 = atomicInteger.compareAndSet(0, 1);
//                if (b1){
//                    return  true;
//                }
//            }
//        }
        if (b){
            currentThread=Thread.currentThread();
        }
        return  b;
    }

    /*
      释放锁
     */
    public   boolean  unLock(){
        //不是获取到锁的线程，那么不能释放
        if(currentThread==null&&currentThread!=Thread.currentThread()){
            return false;
        }
        //将状态从1改为0 ，就证明释放锁
        boolean b = atomicInteger.compareAndSet(1, 0);
        return b;
    }
}
